<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use App\Helper;
use App\Http\Requests\ServerV2StoreRequest;
use App\Http\Requests\ServerV2UpdateRequest;
use App\Models\Goods;
use App\Models\Item;
use App\Models\Mods;
use App\Models\Server;
use App\Models\ServerV2;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;

class ServerV2Controller extends Controller
{

    public $prefix='manager.serverv2';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
//    public function index()
//    {
//        $user=Auth::user();
//        $servers=$user->servers;
//        return view($this->prefix.'.list',compact('servers'));
//    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function create()
    {
        return view($this->prefix.'.create');
    }

    public function create2()
    {
        return view($this->prefix.'.create2');
    }

//    public function ajaxServerTest(Request $request){
//        $data=$request->all();
//        $ip = $data['server_host'];
//        $pwd = $data['root_pwd'];
//        $path =public_path()."\\python\\actTestConnect.py";
//        $command="python $path $ip $pwd";
//        $re = exec($command);
//        $re = iconv('gbk', 'utf-8', $re);
//        return JsonResponse::create(['err'=>0, 'res'=>strpos($re,'Ubuntu')?1:0,'msg'=>$re]);
//    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     */
    public function store(ServerV2StoreRequest $request)
    {
        $data=$request->all();
//        $data['soap_acc']=strtoupper($data['soap_acc']);

        $item=new Server();
        $item->name=$data['name'];
        $item->domain=$data['domain'];
//        $item->server_host=$data['server_host'];
//        $item->root_pwd=$data['root_pwd'];
        $item->type='2';

        $item->ext='{"payforlevel":"0","payforlevelMax":"60","moneyForPerLevel":"10","timetomoney":"0","timetoscore":"0","timetomoneyRatio":"10","bgUrl":null,"loginUrl":null}';

//        $item->fill($data);
        $item->user_id=Auth::id();
        $item->endTime=Carbon::now()->addDays(config('conf.default.newServerFreeDays'));
        $item->ratio=config('conf.default.serverRatio');
        $item->state= 0 ; //config('conf.default.serverState');
        $item->save();
        return redirect('manager/server');
    }

    /**
     * 添加镜像服务器
     * @param ServerV2StoreRequest $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store2(ServerV2StoreRequest $request)
    {
        $data=$request->all();
        if (!isset($data['root_pwd'])) $data['root_pwd']='yun@789..com'; //适配欧赛云默认密码

//        dd($data);

        $item=new Server();
        $item->name=$data['name'];
        $item->domain=$data['domain'];
        $item->server_host=$data['server_host'];
        $item->type='2';
        $item->version=$data['version'];

        $item->root_pwd=$data['root_pwd'];
        $item->server_port='8085';
        $item->auth_port='3724';
        $item->db_host=$data['server_host'];
        $item->db_port='3306';
        $item->db_acc='root';
        $item->db_pwd='g6HBFLKE3tTw';
        $item->soap_host=$data['server_host'];
        $item->soap_port='7878';
//        $item->soap_acc='ADMIN';
//        $item->soap_pwd='g6HBFLKE3tTw';
        $item->path='';
        $item->configPath='/azerothcore/env/dist/etc/worldserver.conf';
        $item->luaPath='/azerothcore/env/dist/bin/lua_scripts';

        $item->ext='{"payforlevel":"0","payforlevelMax":"60","moneyForPerLevel":"10","timetomoney":"0","timetoscore":"0","timetomoneyRatio":"10","bgUrl":null,"loginUrl":null}';

//        $item->fill($data);
        $item->user_id=Auth::id();
        $item->endTime=Carbon::now()->addDays(config('conf.default.newServerFreeDays'));
        $item->ratio=config('conf.default.serverRatio');
        $item->state= 0 ; //config('conf.default.serverState');
        $item->save();
        return redirect('manager/server');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function show($id)
    {
        $server=$this->CheckServer($id);
//        dd($server->getLuaList());
//        dd($server->luaList());
//        dd($server->getLuaScript('超级炉石.lua'));
//        dd($server->SaveFileBody($server->path.$server->luaPath.'/超级炉石1.lua','哈哈哈'));
        return view($this->prefix.'.info',compact('server'));
    }
    public function ajaxServerInfo($id){
        $server=$this->CheckServer($id);
//        $server =ServerV2::find($id);

//        if (strlen($server->mods)===0) $server->mods='eluna';
        $server->mods=$server->mods?explode( ',',$server->mods):[];
        $mods=Mods::where('status',1)->select(['name','flag'])->get();
        return JsonResponse::create(['err'=>0, 'res'=>1,'data'=>['server'=>$server,'mods'=>$mods]]);
    }
    public function ajaxServerTest($id){
        $server=$this->CheckServer($id);
        $res=$server->serverTest();
        $res['err']=0;
        return JsonResponse::create($res);
    }
    public function ajaxInstallInfo($id){
        $server=$this->CheckServer($id);
        $res=$server->getInstallInfo();
        $res['err']=0;
        return JsonResponse::create($res);
    }
    public function ajaxSaveServer(Request $request,$id){
        $server=$this->CheckServer($id);
        $data=$request->all();
        $server->server_host=$data['server_host'];
        $server->root_pwd=$data['root_pwd'];
        if ($request->has('root_port'))
            $server->root_port=$data['root_port'];

        $res=$server->serverTest();
        if ($res['res']===1){

            //检查IP是否重复
//            $sList=Server::where('server_host',$data['server_host'])->get();
//            if (sizeof($sList)==0 || (sizeof($sList)>0 && $sList[0]->id === $server->id)){
                if (!$server->db_pwd){
                    $server->server_port=8085;
                    $server->auth_port=3724;
                    $server->db_host=$server->server_host;
                    $server->db_port=3306;
                    $server->db_acc='root';
                    $server->db_pwd='wowmanage.cn';//Helper::getRandStr(12);
                    $server->soap_host=$server->server_host;
                    $server->soap_port=7878;
                    // $server->soap_acc='ADMIN';
                    // $server->soap_pwd=$server->db_pwd;

//                    $server->path='/azerothcore';
                    $server->configPath='/azerothcore/env/dist/etc/worldserver.conf';
                    $server->luaPath='/azerothcore/env/dist/bin/lua_scripts';
                }
                $server->save();
//            }else{
//                return JsonResponse::create(['err'=>1,'msg'=>'服务器IP已经存在']);
//            }
//            return JsonResponse::create(['err'=>0, 'res'=>1,'data'=>$server]);
        }
//        $res['msg']=$server->db_pwd;
        $res['err']=0;
        return JsonResponse::create($res);
    }
//    public function ajaxSaveBT(Request $request,$id){
//        $server=$this->CheckServer($id);
//        $data=$request->all();
//        $server->bt_url=$data['bt_url'];
//        $server->bt_key=$data['bt_key'];
//        $bt=$server->checkBTAPI();
//        if (isset($bt['data']['version'])){
//            $server->save();
//            return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$bt]);
//        }else{
//            return JsonResponse::create(['err'=>0,'res'=>0,'data'=>$bt]);
//        }
//    }
//    public function ajaxCheckBT($id){
//        $server=$this->CheckServer($id);
//        $bt=$server->checkBTAPI();
//        if (isset($bt['data']['version'])){
//            return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$bt]);
//        }else{
//            return JsonResponse::create(['err'=>0,'res'=>0,'data'=>$bt]);
//        }
//    }
    public function ajaxInstallNew(Request $request,$id){
        $server=$this->CheckServer($id);
        $server->mods=implode(',',$request->get('mods')??[]);
        $server->version=$request->get('version');
        $server->save();
        $res=$server->installAll();
        $res['err']=0;
        return JsonResponse::create($res);
    }
    public function ajaxRunSQL(Request $request,$id){
        $server=$this->CheckServer($id);
        $res=$server->runSQLFile($request->get('act'));
        $res['err']=0;
        return JsonResponse::create($res);
    }
    public function ajaxServerUpdate(Request $request,$id){
        $server=$this->CheckServer($id);
//        $server->mods=implode(',',$request->get('mods')); //$data['mods'];
//        $server->save();
        $res=$server->serverUpdate();
        $res['err']=0;
        return JsonResponse::create($res);
    }
    public function ajaxServerPull(Request $request,$id){
        $server=$this->CheckServer($id);
        $res=$server->serverPull();
        $res['err']=0;
        return JsonResponse::create($res);
    }
//    public function ajaxGetBT($id){
//        $server=$this->CheckServer($id);
//        $res=$server->getBT();
//        $res['err']=0;
//        return JsonResponse::create($res);
//    }

    public function ajaxServerStatus($id){
        $server=$this->CheckServer($id);
        $res=$server->serverStatus();
        $res['err']=0;
        return JsonResponse::create($res);
    }

    public function ajaxServerStart($id){
        $server=$this->CheckServer($id);
        $res=$server->serverStart();
        $server->setAdmin();
        $res['err']=0;
        return JsonResponse::create($res);
    }

    public function ajaxServerStop($id){
        $server=$this->CheckServer($id);
        $res=$server->serverStop();
        $res['err']=0;
        return JsonResponse::create($res);
    }

    public function ajaxTelnet(Request $request,$id){
        $server=$this->CheckServer($id);
        $data=$request->all();
        $res=$server->telnet($data['port']);
        return JsonResponse::create(['err'=>0,'res'=>$res]);
    }
//    public function ajaxCheckBTAPI($id){
//        $server=$this->CheckServer($id);
//        $msg='';
//        try {
//            $msg=$server->checkBTAPI();
//        }catch (Exception $e){
//            return JsonResponse::create(['err'=>0,'res'=>1,'msg'=>$msg]);
//        }
//        return JsonResponse::create(['err'=>0,'res'=>1,'msg'=>$msg]);
//    }




    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function edit($id)
    {
        $server =Server::find($id);
        return view($this->prefix.'.edit',compact('server'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     */
    public function update(ServerV2UpdateRequest $request, $id)
    {
        $data=$request->all();
        $data['soap_acc']=strtoupper($data['soap_acc']);
        $item=Server::find($id);
        //dd($request->all());
        $item->fill($data);
        $item->save();
        return redirect('manager/server');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        $item=Server::find($id);
        $item->delete();
        return redirect('manager/server')->with('msg','删除成功');
    }

    public function command(Request $request,$id){
        $server=$this->CheckServer($id);
        $command=$request->get('command');
        $res='';
        $err='';
        $server->RunCommand('.'.$command,$res,$err);

        if ($err){
            return back()->with('msg','<span class="badge badge-danger">错误</span> '.$err);
        }else{
            return back()->with('msg','<span class="badge badge-success">成功</span> '.$res);
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws Exception
     */
    protected function CheckServer($id){
        $server=ServerV2::find($id);
        $user=Auth::user();
        if ($user->is_admin==1 || $server->user_id==Auth::id()){
            return $server;
        }else{
            throw new Exception('无权访问次服务器',401);
        }
    }


    public function mall($id){

        $server=$this->CheckServer($id);

        Helper::setDataBaseConf('mysql_world',$server,'acore_world');

        return view($this->prefix.'.mall',['server'=>$server]);
    }



    public function goodsSearch(Request $request,$id){
        $server=$this->CheckServer($id);
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');
        $key = $request->get('key');

        if (!$key){
            return JsonResponse::create(['err'=>1,'msg'=>'请输入查询关键字']);
        }
        $item=new Item();
        $list=Item::search($key);
        foreach ($list as $item){
            $item->item;
        }
        return JsonResponse::create(['err'=>0,'data'=>$list->toArray()]);
    }

    public function  goodsAdd(Request $request,$id){
        $server=$this->CheckServer($id);
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');

        $item_id=$request->get('item_id');
        $count=Goods::where('server_id',$id)->where('item_id',$item_id)->count();
        if ($count>0){
            return JsonResponse::create(['err'=>1,'msg'=>'此物品已经在出售中']);
        }

        $count_all=Goods::where('server_id',$id)->count();
        if ($count_all>=config('conf.goodsCountMax')){
            return JsonResponse::create(['err'=>1,'msg'=>'出售商品数量已满']);
        }

        $goods=new Goods();
        $goods->fill($request->all());
        $goods->server_id=$id;
        $goods->save();
        $goods->item;
        return JsonResponse::create(['err'=>0,'data'=>$goods]);

    }

    public function  goodsUpdate(Request $request,$id){
        $server=$this->CheckServer($id);
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');


        $item=Goods::find($request->get('id'));
        if (!$item){
            return JsonResponse::create(['err'=>1,'msg'=>'无效的商品']);
        }else{
            $item->price=$request->get('price');
            $item->save();
            return JsonResponse::create(['err'=>0,'data'=>$item]);
        }
    }
    public function  goodsRemove(Request $request,$id){
        $server=$this->CheckServer($id);
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');

        $item=Goods::find($request->get('id'));
        if (!$item){
            return JsonResponse::create(['err'=>1,'msg'=>'无效的商品']);
        }else{
            $item->delete();
            return JsonResponse::create(['err'=>0]);
        }
    }

    public function goodsList($id){
        $server=$this->CheckServer($id);
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');

        $list=$server->goods;
        foreach ($list as $item){
            $item->item;
        }
        return JsonResponse::create(['err'=>0,'data'=>$list]);
    }

    public function config(Request $request,$id){
        $server=$this->CheckServer($id);
//        dd($server->ext);
        return view($this->prefix.'.config',['server'=>$server]);
    }

    public function configBase($id){
        $server=$this->CheckServer($id);
        return JsonResponse::create(['err'=>0,'data'=>$server->ext]);
    }

//    public function configBaseUpdate(Request $request,$id){
//        $server=$this->CheckServer($id);
//
//        $data=$request->get('data');
//        $server->template= $request->get('tmp');
//        $server->ext= json_encode($data);
//        $server->save();
//
//        return JsonResponse::create(['err'=>0,'data'=>$data]);
//    }

    public function getWorldServerConf(Request $request){
        $id=$request->get('id');
        $server=$this->CheckServer($id);
        $data = $server->getWorldServerConf();
        return JsonResponse::create(['err'=>0,'data'=>$data,'info'=>$server->BtApi->getInfo()]);
    }

    public function saveWorldServerConf(Request $request){
        $id=$request->get('id');
        $server=$this->CheckServer($id);
        $dataStr=$request->get('data');
        $server->world_server_conf=$dataStr;
        $server->save();
        $data=json_decode($dataStr);

        $WorldServerConfString = <<<___


[worldserver]

LogLevel = 2
CloseIdleConnections = 0

SOAP.Enabled = 1
SOAP.IP = "0.0.0.0"
SOAP.Port = 7878


# 自定义属性

___;


        foreach ($data as $k=>$v){
            if ($v->type=='string'){
                $WorldServerConfString .= <<<___
$k = "$v->value"

___;
            }else{
                $WorldServerConfString .= <<<___
$k = $v->value

___;
            }

        }

        $res = $server->saveWorldServerConf($WorldServerConfString);
        return JsonResponse::create(['err'=>0, 'res'=>$res, 'data'=>'']);
    }

    public function lua($id){
        $server=$this->CheckServer($id);
        return view($this->prefix.'.lua',compact('server'));
    }
    public function luaList($id){
        $server=$this->CheckServer($id);
        $files=$server->luaList();
        return JsonResponse::create(['err'=>0, 'res'=>$files, 'data'=>'']);
    }
    public function luaAdd(Request $request,$id){
        $server=$this->CheckServer($id);
        $name=$request->get('name');
        $script=$request->get('script');
        $res1=$server->createLuaFile($name.'.lua');
        $res2=$server->saveLuaFile($name.'.lua',$script);
        return JsonResponse::create(['err'=>0, 'res'=>[
            'create'=>$res1,
            'save'=>$res2,
        ]]);
    }

    public function luaDel(Request $request,$id){
        $server=$this->CheckServer($id);
        $name=$request->get('name');
        $type=$request->get('type');
        $res=$server->delLuaFile($name.'.'.$type);
        return JsonResponse::create(['err'=>0, 'res'=>$res]);
    }

    public function luaStatus(Request $request,$id){
        $server=$this->CheckServer($id);
        $name=$request->get('name');
        $typeNew=$request->get('type');
        $typeOld=($typeNew=='lua'?'lua-':'lua');
        $res=$server->changeLuaStatus($name.'.'.$typeOld,$name.'.'.$typeNew);

        return JsonResponse::create(['err'=>0, 'res'=>$res]);
    }

    public function luaRename(Request $request,$id){
        $server=$this->CheckServer($id);
        $name_old=$request->get('name_old');
        $name=$request->get('name');
        $type=$request->get('type');
        $res=$server->renameLuaFile($name_old.'.'.$type,$name.'.'.$type);
        return JsonResponse::create(['err'=>0, 'res'=>$res]);
    }

    public function luaScript(Request $request,$id){
        $server=$this->CheckServer($id);
        $name=$request->get('name');
        $type=$request->get('type');
        $res=$server->getLuaScript($name.'.'.$type);
        return JsonResponse::create(['err'=>0, 'res'=>$res]);
    }
    public function luaUpdate(Request $request,$id){
        $server=$this->CheckServer($id);
        $name=$request->get('name');
        $type=$request->get('type');
        $data=$request->get('script');
        $res=$server->setLuaScript($name.'.'.$type,$data);
        return JsonResponse::create(['err'=>0, 'res'=>$res]);
    }
    public function luaReload($id){
        $server=$this->CheckServer($id);
        $res='';
        $err='';
        $server->ReloadEluna($res,$err);
        if ($err) {
            return JsonResponse::create(['err'=>1,'msg'=>$err]);
        }else{
            return JsonResponse::create(['err'=>0,'data'=>$res]);
        }
    }
}
